# -*- coding: utf-8 -*-
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from itsdangerous import TimedJSONWebSignatureSerializer as Serilazer

from train import settings
from user.models import User

serilazer = Serilazer(settings.SECRET_KEY, 3600 * 24)


class MyAuthentication(BaseAuthentication):
    '''身份认证'''

    def authenticate(self, request):
        token = request.META.get("HTTP_AUTHORIZATION", "")
        if token == "":
            token = request.META.get("HTTP_TOKEN", "")
        if token == "":
            raise AuthenticationFailed
        decode_token = serilazer.loads(token)
        try:
            username = decode_token.get('username')
            user = User.objects.filter(username=username)
            if len(user) == 0:
                    raise AuthenticationFailed
        except Exception:
            raise AuthenticationFailed
        return user.first(), token
